package com.iweb.controller;

import com.iweb.constant.UrlRequest;
import com.iweb.pojo.Commodity;
import com.iweb.result.DataGrid;
import com.iweb.service.CommodityService;
import com.iweb.utils.JsonWriter;
import com.iweb.utils.UrlUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebServlet("/commodity/*")
public class CommodityServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = UrlUtil.url(req.getRequestURI(), UrlRequest.COMMODITY_URL);
        log.info("用户请求{}", action);
        // 分页的动作
        if ("/findByPage".equals(action)) handlerFindByPage(req, resp);
        if ("/detail".equals(action)) handlerDetail(req, resp);
    }

    private void handlerDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TO DO
        // 获取商品id
        String id = req.getParameter("id");
        System.out.println(id);

        // 调用 CommodityService的 findCommodityById的到商品明细数据

        // 将商品对象封装到 HttpServletRequest 中  key commodity

        // 返回视图
        req.getRequestDispatcher("/views/details/details.jsp").forward(req, resp);
    }

    // http://localhost:8090/commodity/findByPage?current=1&size=10
    // 处理分页  http://localhost:8090/commodity/findByPage?current=1&size=10
    private void handlerFindByPage(HttpServletRequest req, HttpServletResponse resp) {
        CommodityService commodityService = new CommodityService();

        // 获取请求参数 current size 并转型 long
        String currentStr = req.getParameter("current");
        String sizeStr = req.getParameter("size");
        long current = Long.parseLong(currentStr);
        long size = Long.parseLong(sizeStr);

        // 调用service接口返回分页对象
        DataGrid<Commodity> dataGrid = commodityService.findByPage(current, size);
        // 通过 response 写回数据
        JsonWriter.writer(resp, dataGrid);
    }
}
